package com.example.demo.entity.response;

import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * @version 1.0
 * @Author: LJP
 * @Description:        统一返回类定义
 * @Date: Created in 15:15 2021/11/30
 */
@Data
@NoArgsConstructor
@SuppressWarnings(value = {"unused"})
public class Result<T> implements Serializable {

    /**
     * 定义序列化时使用的版本UID
     * 在进行反序列化时，JVM会把传来的字节流中的serialVersionUID与本地相应实体（类）的serialVersionUID进行比较
     * 如果相同就认为是一致的，可以进行反序列化，否则就会出现序列化版本不一致的异常
     */
    private static final long serialVersionUID = -3948389268046368059L;

    /**
     * 状态码
     */
    private Integer code;

    /**
     * 请求提示消息
     */
    private String msg;

    /**
     * 返回数据
     */
    private T data;

    private Result(T data){
        this.code = 20000;
        this.msg = "操作成功";
        this.data = data;
    }

    private Result(Integer code,String msg,T data){
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static <T> Result<T> success() {
        Result<T> result = new Result<>();
        result.setResultCode(ResultCodeEnum.SUCCESS);
        return result;
    }

    public static <T> Result<T> failure(ResultCodeEnum resultCodeEnum) {
        Result<T> result = new Result<>();
        result.setResultCode(resultCodeEnum);
        return result;
    }

    //自定义相应失败值
    public static <T> Result<T> failure(String failMsg) {
        Result<T> result = new Result<>();
        result.setMsg(failMsg);
        result.setCode(10000);
        return result;
    }


    public void setResultCode(ResultCodeEnum code) {
        this.code = code.code();
        this.msg = code.msg();
    }

    // 自定义返回数据
    public Result<T> data(T data) {
        this.setData(data);
        return this;
    }

    // 自定义状态信息
    public Result<T> msg(String message) {
        this.setMsg(message);
        return this;
    }

    // 自定义状态码
    public Result<T> code(Integer code) {
        this.setCode(code);
        return this;
    }

}
